<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="500px" :height="200" destroyOnClose>
    <div :class="prefixCls">
      <div :class="prefixCls + '-image'">
        <img
          v-if="randCodeData.requestCodeSuccess"
          style="margin-top: 2px; width: 300px; height: 120px;"
          :src="randCodeData.randCodeImage"
          @click="handleChangeCheckCode"
        />
        <img v-else 
          style="margin-top: 2px; width: 300px; height: 120px;" 
          :src="checkCodeImage" @click="handleChangeCheckCode" 
        />
      </div>

      <div :class="prefixCls + '-input'">
        <a-input v-model:value="randCodeData.imageCaptcha" placeholder="图形验证码" style="min-width: 100px" />
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import {reactive, ref} from 'vue';
import {useMessage} from '/@/hooks/web/useMessage';
import {useDesign} from '/@/hooks/web/useDesign';
import {BasicModal, useModalInner} from '/@/components/Modal';
import {useUserStore} from '/@/store/modules/user';
import {checkImageCaptcha, getImageCaptcha} from '/@/api/sys/user';
import checkCodeImage from '/@/assets/images/checkcode.png'

const userStore = useUserStore();
const emit = defineEmits(['register', 'submit']);
const title = ref('人机验证')
const { createMessage } = useMessage();
const { prefixCls } = useDesign('man-machine-verify');
const randCodeData = reactive({
  randCodeImage: '',
  imageCaptcha: '',
  requestCodeSuccess: false,
  uuid: null,
});

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  console.log('data', data);
  setModalProps({ 
    canFullscreen: false, defaultFullscreen: false,
    showCancelBtn: false, okText: '验证',
  })
  handleChangeCheckCode()
});

const handleSubmit = async () => {
  const data = {imageCaptcha: randCodeData.imageCaptcha, uuid: randCodeData.uuid}
  const ret = await checkImageCaptcha(data)
  if (!ret) {
    createMessage.error('验证码错误')
    handleChangeCheckCode()
    return
  }
  emit('submit', data)
  closeModal()
}

const handleChangeCheckCode = () => {
  randCodeData.imageCaptcha = ''
  //TODO 兼容mock和接口，暂时这样处理
  getImageCaptcha().then(res=>{
    randCodeData.randCodeImage = res.img
    randCodeData.requestCodeSuccess = true
    randCodeData.uuid = res.uuid
  });
}

</script>

<style lang="less">
 @prefix-cls: ~'@{namespace}-man-machine-verify';

 .@{prefix-cls} {
  display: flex;
  margin: 5px;
  justify-content: center; 
  flex-direction: column;
  align-items:center;/*由于flex-direction: column，因此align-items代表的是水平方向*/
  justify-content: center;/*由于flex-direction: column，因此justify-content代表的是垂直方向*/

  &-image {
    margin-bottom: 20px;
    width: 300px;
  }

  &-input {
    width: 90%;
  }
 }
 
</style>
